package com.dailyblue.java.mybatis.mybatis05;

import com.dailyblue.java.mybatis.mybatis05.bean.Emp;
import com.dailyblue.java.mybatis.mybatis05.mapper.EmpMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class App {
    private static SqlSession session1;
    private static SqlSession session2;
    private static EmpMapper mapper1;
    private static EmpMapper mapper2;

    static {
        try {
            InputStream in = Resources.getResourceAsStream("config.xml");
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
            // 这里创建了2个会话
            session1 = ssf.openSession();
            session2 = ssf.openSession();
            // 分别用2个会话创建了2个对象
            mapper1 = session1.getMapper(EmpMapper.class);
            mapper2 = session2.getMapper(EmpMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void a() {
        // 这里调用了2次查询6号员工的操作，但是只链接一次数据库，这个就是一级缓存
        Emp emp1 = mapper1.findEmpByNo(6);
        // 清空缓存
        session1.clearCache();
        Emp emp2 = mapper1.findEmpByNo(6);
        System.out.println(emp1);
        System.out.println(emp2);
    }

    // 一级缓存失效情况1
    private static void b() {
        Emp emp1 = mapper1.findEmpByNo(6);
        Emp emp2 = mapper2.findEmpByNo(6);
        System.out.println(emp1);
        System.out.println(emp2);
    }

    // 一级缓存失效情况2
    private static void c() {
        Emp emp1 = mapper1.findEmpByNo(6);
        mapper1.deleteEmp(9999);
        Emp emp2 = mapper1.findEmpByNo(6);
        System.out.println(emp1);
        System.out.println(emp2);
    }

    // 二级缓存

    private static void d() {
        Emp emp1 = mapper1.findEmpByNo(6);
        // 关闭session1
        session1.close();
        Emp emp2 = mapper2.findEmpByNo(6);
        System.out.println(emp1);
        System.out.println(emp2);
    }

    public static void main(String[] args) {
        d();
    }
}
